import { findDicByCode } from '@/support/common';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  message,
  PageHeader,
  Popconfirm,
  Row,
  Select,
} from 'antd';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';

const mapStateToProps = (state: any) => ({
  ipda: state.ipda2,
  loading: state.loading.effects['ipda2/getFetchPage'],
});

// const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 0 },
    sm: { span: 0 },
  },
  wrapperCol: {
    xs: { span: 0 },
    sm: { span: 0 },
    md: { span: 0 },
  },
};
const fieldLabels = {
  projectId: '项目',
  deviceId: '设备编号',
  deviceName: '设备名称',
  versionHardware: '硬件版本号',
  versionSoftware: '软件版本号',
  batchNo: '批次号',
  deviceStatus: '设备状态',
  enrollDate: '激活时间',
  produceDate: '生产日期 ',
  publishDate: '发布日期',
  dynamicSecretkey: '动态秘钥',
};

class IpdaEdit extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();

  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.any,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      projectIdData: [],
      query: {},
      buttonLoading: false,
    };
  }

  componentWillMount() {
    if (this.props.location && this.props.location.state) {
      this.setState({
        query: this.props.location.state.obj,
      });
    }
  }
  componentDidMount() {
    const { dispatch } = this.props;

    if (this.props.location.flag) {
      const record = this.props.location.state.data.data;
      this.formRef.current?.resetFields();
      this.formRef.current?.setFieldsValue({
        deviceId: record.deviceId,
        deviceName: record.deviceName,
        versionHardware: record.versionHardware,
        versionSoftware: record.versionSoftware,
        batchNo: record.batchNo,
        deviceStatus:
          record.deviceStatus === null ? record.deviceStatus : record.deviceStatus.toString(),
        enrollDate: record.enrollDate === null ? record.enrollDate : moment(record.enrollDate),
        produceDate: record.produceDate === null ? record.produceDate : moment(record.produceDate),
        publishDate: record.publishDate === null ? record.publishDate : moment(record.publishDate),
        sid: record.sid,
        dynamicSecretkey: record.dynamicSecretkey,
        createDate: record.createDate,
        createBy: record.createBy,
        delFlag: record.delFlag,
        version: record.version,
      });
    } else {
      dispatch({
        type: 'ipda2/getDataWithRes',
        payload: { url: '/basedata/findprojectbylogin' },
        callback: data => {
          this.setState({
            projectIdData: data,
          });
        },
      });
    }
  }
  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  };
  canceledit = () => {
    const { query } = this.state;
    const { dispatch } = this.props;
    this.formRef.current?.resetFields();
    dispatch(routerRedux.push({ pathname: '/connectPlat/ipda', state: { query } }));
  };
  render() {
    const { buttonLoading } = this.state;

    const { dispatch } = this.props;
    const a = findDicByCode(this.context.dicData, 'deviceStatus');
    const projectIdData = a.map(d => (
      <Select.Option value={d.dictKey} key={d.dictKey}>
        {d.dictValue}
      </Select.Option>
    ));

    const ok = (values: any) => {
      if (values) {
        this.setState({
          buttonLoading: true,
        });
        const { query } = this.state;
        const url = 'ipda/edit';
        const obj = values;

        if (url === 'ipda/edit') {
          if (values.produceDate) {
            obj.produceDate = new Date(values.produceDate);
          }
          if (values.enrollDate) {
            obj.enrollDate = new Date(values.enrollDate);
          }
          if (values.publishDate) {
            obj.publishDate = new Date(values.publishDate);
          }
          if (values.createDate) {
            obj.createDate = new Date(values.createDate);
          }
        }
        dispatch({
          type: 'ipda2/postObjWithRes',
          payload: { url: '/ipda/edit', ...obj },
          callback: response => {
            if (response.statusCode === '0') {
              message.success('操作成功');
              if (url === 'ipda/edit') {
                dispatch(routerRedux.push({ pathname: '/connectPlat/ipda', state: { query } }));
              } else {
                dispatch(routerRedux.push('/connectPlat/ipda'));
              }
              //  this.props.history.push('/connectPlat/ipda',state: { query } )
            } else {
              message.error(response.statusMessage, 3);
            }
            this.setState({
              buttonLoading: false,
            });
          },
        });
      }
    };

    const validate = () => {
      this.formRef.current?.submit();
    };

    if (this.props.location.flag) {
      return (
        <div>
          <Card title="" bordered={false}>
            <Form layout="vertical" hideRequiredMark ref={this.formRef} onFinish={ok}>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.deviceId}
                    name="deviceId"
                    rules={[{ required: true, message: '设备ID' }]}
                  >
                    <Input maxLength="20" placeholder="请输入设备ID" disabled />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.deviceName}
                    name="deviceName"
                    rules={[{ required: true, message: '设备名称' }]}
                  >
                    <Input maxLength="50" placeholder="请输入设备名称" />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.deviceStatus}
                    name="deviceStatus"
                    rules={[{ required: false, message: '设备状态' }]}
                  >
                    <Select
                      placeholder="请设置设备状态"
                      allowClear
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                    >
                      {projectIdData}
                      {/* <Select.Option value="0">出厂</Select.Option>
                      <Select.Option value="1">销售</Select.Option>
                      <Select.Option value="2">激活</Select.Option>
                      <Select.Option value="3">替换</Select.Option>
                      <Select.Option value="4">报废</Select.Option> */}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.versionHardware}
                    name="versionHardware"
                    rules={[{ required: false, message: '硬件版本号' }]}
                  >
                    <Input placeholder="请输入硬件版本号" />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.versionSoftware}
                    name="versionSoftware"
                    rules={[{ required: false, message: '软件版本号' }]}
                  >
                    <Input placeholder="请输入软件版本号" />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.batchNo}
                    name="batchNo"
                    rules={[{ required: false, message: '设备批次号' }]}
                  >
                    <Input placeholder="请输入批次号" maxLength={100} />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.produceDate}
                    name="produceDate"
                    rules={[{ required: false, message: '生产日期' }]}
                  >
                    <DatePicker
                      style={{ width: '100%' }}
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      placeholder="生产日期"
                      disabled
                    />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.publishDate}
                    name="publishDate"
                    rules={[{ required: false, message: '发布日期' }]}
                  >
                    <DatePicker
                      style={{ width: '100%' }}
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      placeholder="发布日期"
                      disabled
                    />
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.enrollDate}
                    name="enrollDate"
                    rules={[{ required: false, message: '激活时间' }]}
                  >
                    <DatePicker
                      style={{ width: '100%' }}
                      placeholder="激活时间"
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      disabled
                    />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    {...formItemLayout}
                    label={fieldLabels.dynamicSecretkey}
                    name="dynamicSecretkey"
                    rules={[{ required: false, message: '动态秘钥超长', max: 50 }]}
                  >
                    <Input placeholder="请输入动态秘钥" />
                  </Form.Item>
                </Col>
              </Row>
              <Col>
                <Form.Item style={{ display: 'none' }} label="" name="sid">
                  <input type="text" />
                </Form.Item>
                <Form.Item style={{ display: 'none' }} label="" name="createDate">
                  <input type="text" />
                </Form.Item>
                <Form.Item style={{ display: 'none' }} label="" name="createBy">
                  <input type="text" />
                </Form.Item>
                <Form.Item style={{ display: 'none' }} label="" name="version">
                  <input type="text" />
                </Form.Item>
                <Form.Item style={{ display: 'none' }} label="" name="delFlag">
                  <input type="text" />
                </Form.Item>
              </Col>
            </Form>
            <Form layout="vertical" hideRequiredMark>
              <Row gutter={16}>
                <Col xl={{ span: 5, offset: 9 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                  <div>
                    <Button
                      loading={buttonLoading}
                      key="submit"
                      type="primary"
                      size="default"
                      onClick={validate}
                    >
                      提交
                    </Button>
                    &nbsp;&nbsp;
                    <Popconfirm
                      title={this.props.location.flag ? '确定放弃编辑吗?' : '确定放弃添加吗?'}
                      onConfirm={() => this.props.history.goBack()}
                    >
                      <Button key="back" size="default">
                        取消
                      </Button>
                    </Popconfirm>
                  </div>
                </Col>
              </Row>
            </Form>
          </Card>
        </div>
      );
    } else {
      return (
        <PageHeader title="">
          <div align="center" width="100%" height="100%">
            <h2>未选择任何车机,请返回列表重新选择</h2>
            <a onClick={() => this.canceledit()}>返回</a>
          </div>
        </PageHeader>
      );
    }
  }
}

export default connect(mapStateToProps)(IpdaEdit);
